let urls = require("../server/Urls.js")
// const companyId = '3171776001692663894'; //租户ID
// const platformId = '9609977215975480'; //平台ID
const companyId = '3171776001692663893'; //租户ID
const platformId = '3189609977215975481'; //平台ID
/**
 * 假设返回结构
 * {
 *  code:0,//0:表示返回正确数据 其他：错误数据
 *  data:{}, //code = 0时，返回的数据，可为空
 *  msg:"" //code非0时返回的错误信息
 * }
 */



/***********************************************
 *  接口  START                                 *
 ***********************************************/

/**
 * 微信授权登录
 *wx_name	varchar	255			微信名称			
 *wx_pic	varchar	255		微信头像			
 *wx_country	varchar		国家			
 *wx_province	varchar		省份			
 *wx_city	varchar	城市			
 * 
 */
function wxLogin(params) {
  return post(urls.Url_wx_login, params)
}
function ttLogin(params) {
  return post(urls.Url_tt_login, params)
}

function getShareInfo(userId, type, id) {
  return post(urls.Url_user_get_share_info, {
    businessId: id,
    companyId: companyId,
    platformId: platformId,
    type: type,
    userId: userId
  })
}

function getShareInfoByScene(scene) {
  return post(urls.Url_get_scene_share_info + "/" + scene, {})
}

function getConsumerById(userId) {
  return get(urls.Url_get_consumer_by_id + "/" + userId)
}

function getUserCode(userId) {
  return get(urls.Url_user_code + "/" + userId)
}

/**
 * 查询首页商品列表
 * pageSize 
 * pageNumber 
 * platformId: app.globalData.platformId,
 * companyId: app.globalData.companyId
 */
function queryShops(params) {
  return post(urls.Url_query_shops, params)
}

function getNearestShop(latitude, longitude, userId) {
  var params = {
    "latitude": latitude,
    "longitude": longitude,
    "pageNumber": 1,
    "pageSize": 1000,
    "platId": platformId,
    "userId": userId
  }
  return post(urls.Url_get_nearest_shop, params)
}

function getShopInfo(id) {
  return get(urls.Url_get_shop + "/" + id)
}

function queryShopCategories(id) {
  return get(urls.Url_get_shop_categories + "/" + id)
}

function getCategoryAndGoods(id) {
  return post(urls.Url_get_category_and_goods, {
    pageNumber: "1",
    pageSize: "100",
    platformid: platformId,
    storeId: id
  })
}

function getStoresByUserId(memberid) {
  return post(urls.Url_get_stores_by_user_id, {
    memberId: memberid,
    platId: platformId,
    pageNumber: "1",
    pageSize: "5"
  })
}

function getStoresByPlatId() {
  return get(urls.Url_get_stores_by_plat_id + "/" + platformId)
}

function batchUpdateStores(storeDtos) {
  return post(urls.Url_batch_update_stores, storeDtos);
}

function queryCategoryGoods(storeId, categoryId, pageNumber, pageSize) {
  let params = {
    storeId: storeId,
    categoryId: categoryId,
    pageSize: pageSize,
    pageNumber: pageNumber,
    companyid: companyId, //租户ID
    platformid: platformId, //平台ID
  }
  console.log(params);
  return post(urls.Url__query_category_goods, params)
}

/**
 * 查询首页商品列表
 * pageSize 
 * pageNumber 
 * platformId: app.globalData.platformId,
 * companyId: app.globalData.companyId
 */
function queryHomeGoods(params) {
  return post(urls.Url_home_goods, params)
}
/**
 * 获等短信验证码
 */
function getVerifyCode(mobileNo) {
  return get(urls.Url_wx_get_verify_code + "/" + mobileNo, {})
}


/**
 * 短信验证码登录
 * code  验证码
 * companyId 租户id
 * platformId 平台id
 * invitationCode 邀请码
 * mobile 手机号
 * msgId  短信id
 */

function loginByCode(params) {

  return post(urls.Url_code_login, params)
}

/**
 * 检测是否登录
 */
function checkLogin(code, companyId, platformId) {
  let params = {
    code: code,
    companyId: companyId, //租户ID
    platformId: platformId, //平台ID
  }
  return post(urls.Url_check_wx_login, params)
}


/**
 * 获取首页轮播图
 */
function queryHomeBanner(storeId) {
  var params = {
    platformId: platformId,
    companyId: companyId,
    storeId: storeId
  }
  return post(urls.Url_query_home_banner, params)
}

/**
 * 查询商品详情
 */
function queryGoodsDetail(id, userId) {
  var params = {
    id: id,
    userId: userId
  }
  return post(urls.Url_get_goods_detail, params);
}

/**
 * 查询商品详情
 */
// function queryGoodsDetail(id, userId) {
//   return get(urls.Url_get_goods_detail + "/" + id);
// }


/**
 * 加入购物车
 */
function addCart(goodsCount, skuId, userId) {
  var params = {
    "goodsQuantity": goodsCount,
    "skuId": skuId,
    "userId": userId
  };
  return post(urls.Url_add_cart, params)
}

//查询购物车
function queryCartList(params) {
  return post(urls.Url_query_cart_count, params)
}
//更新购物车数量
function updateCartCount(recId, goodsQuantity) {
  let params = {
    goodsQuantity: goodsQuantity,
    recId: recId
  }
  return post(urls.Url_update_cart, params);
}

//删除购物车
function deleteCart(id) {
  return _delete(urls.Url_delete_cart + "/" + id, {})
}

//删除购物车
function deleteCartByStoreId(storeId, userId) {
  return _delete(urls.Url_delete_cart_by_storeId, {
    storeId: storeId,
    userId: userId
  })
}


/**
 * 查询收货地址
 */
function queryMyAddress(params) {
  return post(urls.Url_query_address, params)
}

/**
 * 新增收货地址
 */
function addAddress(params) {
  return post(urls.Url_add_address, params)
}

/**
 * 更新收货地址
 * 
 */
function updateAddress(params) {
  return post(urls.Url_update_address, params);
}

//删除收地址
function deleteAddress(id) {
  return _delete(urls.Url_delete_address + "/" + id, {})
}


/*******************物流************************/

//查询物流
function queryLogisticsDetail(orderId) {
  return get(urls.Url_query_logistics_detail + "/" + orderId, {})
}


/*******************订单************************/


//查询订单列表
function queryOrderList(params) {
  return post(urls.Url_order_query_list, params)
}

//查询订单列表
function queryStoreOrderList(params) {
  return post(urls.Url_order_query_store_list, params)
}

//查询店铺订单按提货时间排序列表
function queryStoreOrderListByDeliveryTime(params) {
  return post(urls.Url_order_query_store_delivery_list, params)
}

//获取待核销订单
function queryStoreVerificationOrderListByUserCode(storeId, userCode) {
  return post(urls.Url_order_verification_list, {
    "storeId": storeId,
    "userCode": userCode
  })
}

//一键提醒当天及以前待提货的买家
function notifyBuyersByStoreId(storeId) {
  return get(urls.Url_notify_buyer_by_store + "/" + storeId)
}

//提醒某个待提货的订单的买家
function notifyBuyersByOrderId(orderId) {
  return get(urls.Url_notify_buyer_by_order + "/" + orderId)
}

//查询订单详情
function queryOrderDetail(orderId, lat, lng) {
  return post(urls.Url_order_query_detail, {
    orderId: orderId,
    longitude: lng + "",
    latitude: lat + ""
  })
}

//提交订单
function submitOrder(params) {
  return post(urls.Url_order_submit, params)
}

//支付订单
function payOrder(orderId, userId) {
  let params = {
    orderId: orderId,
    channel: "weixin",
    payMode: "WEBAPP",
    userId: userId
  }
  return post(urls.Url_order_pay, params);
}

//商品购买记录
function orderBuyList(params) {
  return post(urls.Url_order_buy_list, params);
}



//取消订单
function cancelOrder(orderId) {
  return _delete(urls.Url_order_cancel + "/" + orderId, {})
}

//退款订单
function refundOrder(orderId) {
  return post(urls.Url_order_refund, {
    orderId: orderId,
    refundDesc: "待提货-退款"
  })
}

//删除订单
function deleteOrder(orderId) {
  return _delete(urls.Url_order_delete + "/" + orderId, {})
}

//核销订单
function verificationOrder(code, storeId) {
  return post(urls.Url_order_verification_store, {
    code: code,
    storeId: storeId
  })
}

//批量核销订单
function verificationAllOrder(code, storeId) {
  return post(urls.Url_all_order_verification_store, {
    code: code,
    storeId: storeId
  })
}

//修改订单状态
function UpdateOrderStatus(orderId, status) {
  return post(urls.Url_order_update_status, {
    orderId: orderId,
    status: status
  })
}

//查询用户历史收货人和电话
function getHistoryConsigneeAndTelephone(userId) {
  return post(urls.Url_get_user_contacts + "/" + userId, {})
}

//申请售后页面数据
function applyAfterSaleInfo(subId) {
  return get(urls.Url_after_sale_info + "/" + subId, {})
}

//售后列表
function listRefundOrder(userId, pageSize, pageNumber) {
  return post(urls.Url_list_refund_order, {
    "pageNumber": pageNumber,
    "pageSize": pageSize,
    "userId": userId
  })
}

//售后申请
function refundApply(params) {
  return post(urls.Url_refund_apply, params)
}

//售后取消
function refundCancel(params) {
  return put(urls.Url_refund_cancel, params)
}

//售后详情
function refundDetail(subId) {
  return get(urls.Url_refund_detail + "/" + subId, {})
}

//售后详情
function refundDetail2(refundId) {
  return get(urls.Url_refund_detail2 + "/" + refundId, {})
}


//重新发起售后
function refundReApply(params) {
  return put(urls.Url_refund_re_apply, params)
}

//退款图片上传
function refundUploadFile(filePath) {
  return new Promise((resolve, reject) => {
    tt.uploadFile({
      url: urls.Url_refund_upload_file,
      filePath: filePath,
      name: 'file',
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.errno == 401) {
            loginOpertion(success, error)
          } else {
            let result = JSON.parse(res.data)
            if (result.code == 200) {
              resolve(result.data)
            } else {
              reject(result.msg || '接口未知错误')
            }
          }
        } else {
          reject("服务器异常：" + res.data.error);
        }
      },
      fail(res) {
        reject(res)
      }
    })
  });
}

//申请提现
function withdrawalApply(params) {
  return post(urls.Url_withdrawal_apply, params)
}

//进行签约
function contractPlatform(params) {
  return post(urls.Url_contract_platform, params)
}

//查询是否签约
function subscriptionInformation(name, idcard) {
  return post(urls.Url_subscription_information, {
    "name": name,
    "idcard": idcard
  })
}

//查询签约记录
function contractRecord(name, idcard) {
  return post(urls.Url_contract_record, {
    "name": name,
    "idcard": idcard
  })
}

/***********************************************
 *  接口  END                                 *
 ***********************************************/

/***********************************************
 * 网络请求封装  START                            *
 ***********************************************/

function request(url, data = {}, contentType = {
  'content-type': 'application/json'
}, method = "GET") {
  //此处处理接口请求参数公共部分的操作：如加密签名等

  return new Promise(function(success, error) {
    //wx.showLoading()
    tt.request({
      url: url,
      data: data,
      method: method,
      header: contentType,

      success: function(res) {
        //wx.hideLoading();
        // tt.hideNavigationBarLoading();
        //请求成功
        if (res.statusCode == 200) {
          console.log(res.data);
          if (res.data.errno == 401) { //判断调用接口是否需要登陆
            loginOpertion(success, error) //执行登陆操作
          } else {
            let result = res.data
            if (result.code == 200) {
              success(result.data)
            } else {
              error(result.msg || '接口未知错误')
            }
          }
        } else {
          //接口不通
          error("服务器异常：" + res.data.error);
        }
      },
      fail: function(err) {
        tt.hideLoading();
        // tt.hideNavigationBarLoading();
        error("服务器异常")
        console.log(err.errMsg)
      }
    })
  });
}

//get 请求
function get(url, data = {}) {
  return request(url, data, "")
}

function get(url, data = {}, contentType) {
  return request(url, data, contentType)
}

//post 请求
function post(url, data = {}) {
  return request(url, data, "", 'POST')
}

function post(url, data = {}, contentType) {
  return request(url, data, contentType, 'POST')
}

//put 请求
function put(url, data = {}) {
  return request(url, data, "", 'PUT')
}

function put(url, data = {}, contentType) {
  return request(url, data, contentType, 'PUT')
}

//delete 请求
function _delete(url, data = {}) {
  return request(url, data, "", 'DELETE')
}

function _delete(url, data = {}, contentType) {
  return request(url, data, contentType, 'DELETE')
}



/**
 * 需要进行登录的接口---进行登录操作
 */
function loginOpertion(success, error) {
  //需要登录后才可以操作
  let code = null;
  return login().then((res) => {
    code = res.code;
    return getUserInfo();
  }).then((userInfo) => {
    //登录远程服务器
    request(api.AuthLoginByWeixin, {
      code: code,
      userInfo: userInfo
    }, 'POST').then(res => {
      if (res.error === 0) {
        //存储用户信息
        tt.setStorageSync('userInfo', res.data.userInfo);
        tt.setStorageSync('token', res.data.token);
        success(res);
      } else {
        error(res);
      }
    }).catch((err) => {
      error(err);
    });
  }).catch((err) => {
    error(err);
  })
}

/***********************************************
 * 网络请求封装  END                            *
 ***********************************************/

module.exports = {
  //登录
  wxLogin,
  ttLogin,
  getShareInfo,
  getVerifyCode,
  loginByCode,
  checkLogin,
  getUserCode,
  getShareInfoByScene,
  getConsumerById,

  //店铺
  getNearestShop,
  queryShops,
  getShopInfo,
  queryShopCategories,
  getStoresByUserId,
  getCategoryAndGoods,
  getStoresByPlatId,
  batchUpdateStores,

  //商品
  queryCategoryGoods,
  queryHomeGoods,
  queryHomeBanner,
  queryGoodsDetail,
  addCart: addCart,
  deleteCart: deleteCart,
  deleteCartByStoreId: deleteCartByStoreId,
  queryCartList: queryCartList,
  updateCartCount: updateCartCount,

  //物流
  queryLogisticsDetail: queryLogisticsDetail,

  //收货地址
  addAddress: addAddress,
  queryMyAddress: queryMyAddress,
  deleteAddress: deleteAddress,
  updateAddress: updateAddress,

  //订单
  queryOrderList: queryOrderList,
  queryStoreOrderList: queryStoreOrderList,
  queryStoreOrderListByDeliveryTime,
  queryOrderDetail: queryOrderDetail,
  submitOrder: submitOrder,
  payOrder: payOrder,
  orderBuyList: orderBuyList,
  deleteOrder: deleteOrder,
  cancelOrder: cancelOrder,
  refundOrder: refundOrder,
  verificationOrder: verificationOrder,
  verificationAllOrder,
  UpdateOrderStatus: UpdateOrderStatus,
  queryStoreVerificationOrderListByUserCode,
  notifyBuyersByStoreId,
  notifyBuyersByOrderId,
  getHistoryConsigneeAndTelephone,

  withdrawalApply,
  contractPlatform,
  subscriptionInformation,
  contractRecord,

  applyAfterSaleInfo,
  listRefundOrder,
  refundApply,
  refundCancel,
  refundDetail,
  refundDetail2,
  refundReApply,
  refundUploadFile
}